package test.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

import org.apache.log4j.Logger;


/**
 * @author yun
 *
 */
public class ServerThread implements Runnable {
	private final static Logger LOG = Logger.getLogger(ServerThread.class);
	
	Socket socket;
	BufferedReader br = null;
	
	public ServerThread(Socket socket) throws IOException {
		this.socket = socket;
		br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	}
	
	public void run() {
		try {
			String content = null;
			while((content = this.readFromClient()) != null) {
				for(Socket socket : MyServer.socketList) {
					PrintStream printStream = new PrintStream(socket.getOutputStream());
					printStream.println(content);
				}
			}
		} catch (Exception e) {
			LOG.info(e);
		}
	}
	
	public String readFromClient() {
		try {
			return br.readLine();
		} catch (IOException e) {
			LOG.info(e);
			MyServer.socketList.remove(socket);
		}
		return null;
	}
}